package views

import (
	"errors"
	"log"
	"net/http"
	"strconv"
	"study/go-blog/common"
	"study/go-blog/config"
	"study/go-blog/models"
	"study/go-blog/service"
)

// 页面上涉及到的所有的数据，必须有定义
var categorys = []models.Category{
	{
		Cid:  1,
		Name: "go",
	},
}
var posts = []models.PostMore{
	{
		Pid:          1,
		Title:        "go博客",
		Content:      "内容",
		UserName:     "张三",
		ViewCount:    123,
		CreateAt:     "2022-02-20",
		CategoryId:   1,
		CategoryName: "go",
		Type:         0,
	},
}
var hr = &models.HomeResponse{
	Viewer:    config.Cfg.Viewer,
	Categorys: categorys,
	Posts:     posts,
	Total:     1,
	Page:      1,
	Pages:     []int{1},
	PageEnd:   true,
}

func (*HTMLApi) Index(response http.ResponseWriter, request *http.Request) {
	//获取模板
	index := common.Template.Index

	if err := request.ParseForm(); err != nil {
		log.Println("表单获取失败", err)
		index.WriteError(response, errors.New("系统错误，请联系管理员"))
		return
	}

	pageStr := request.Form.Get("page")
	if pageStr == "" {
		pageStr = "1"
	}

	page, _ := strconv.Atoi(pageStr)
	pageSize := 10

	hr, err := service.GetAllIndexInfo(page, pageSize)
	if err != nil {
		log.Println("index获取数据出错：", err)
		index.WriteError(response, errors.New("系统错误，请联系管理员"))
	}
	index.WriteData(response, hr)
}
